package com.yeqian.attachment.config;

import cn.hutool.core.util.StrUtil;

import com.yeqian.attachment.enums.UploadTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

@Slf4j
public class FileCondition {
    public FileCondition() {
    }

    private static Boolean verificationFileType(ConditionContext context, UploadTypeEnum fileUploadType) {
        String fileType = context.getEnvironment().getProperty("yeq.file-config.uploadType");
        if (StrUtil.isBlank(fileType)) {
            fileType = context.getEnvironment().getProperty("yeq.fileConfig.uploadType");
        }

        UploadTypeEnum fileUploadTypeEnum = UploadTypeEnum.getFileUploadType(fileType);
        if (fileUploadTypeEnum == null) {
            if (UploadTypeEnum.LOCAL == fileUploadType) {
                log.error("不存在{}类型的文件上传实现，默认启用本地上传方式", new Object[]{fileType});
                return true;
            } else {
                return false;
            }
        } else {
            return fileUploadType == fileUploadTypeEnum;
        }
    }

    public static class FASTDFSTypeCondition implements Condition {
        public FASTDFSTypeCondition() {
        }

        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            return FileCondition.verificationFileType(context, UploadTypeEnum.FASTDFS);
        }
    }

    public static class LocalTypeCondition implements Condition {
        public LocalTypeCondition() {
        }

        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            return FileCondition.verificationFileType(context, UploadTypeEnum.LOCAL);
        }
    }
}
